import { AdminModule } from './modules/admin/admin.module';
import { RolesGuard } from './guards/roles.guard';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { MiddleLogMiddleware } from './middlewares/middle-log.middleware';
import { Module, NestModule, MiddlewareConsumer, Logger } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { UserModule } from './modules/user/user.module';
import { AuthModule } from './modules/auth/auth.module';
import { WebsocketModule } from './modules/websocket/websocket.module';
import { FileUploadModule } from './modules/file-upload/file-upload.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import customConfig from './config'
import { utilities as nestWinstonModuleUtilities, WinstonModule } from 'nest-winston'
import { BannersModule } from './modules/banners/banners.module';
import { ArticleModule } from './modules/article/article.module';
import { VideoModule } from './modules/video/video.module';

import * as winston from 'winston';
import { APP_GUARD } from '@nestjs/core';
import { WxModule } from './modules/wx/wx.module';
import { ExcelModule } from './modules/excel/excel.module';

@Module({
  imports: [
    WinstonModule.forRoot({
      transports: [
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.timestamp(),
            nestWinstonModuleUtilities.format.nestLike(),
          ),
        }),
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'combined.log' }),
        new winston.transports.File({
          filename: 'errors.log',
          level: 'error',
          // tailable: true, 
        })
      ],
    }),
    ConfigModule.forRoot({
      isGlobal: true,
      load: [customConfig]
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => configService.get('DATABASE_CONFIG'),
      inject: [ConfigService]
    }),
    UserModule,
    AuthModule,
    WebsocketModule,
    FileUploadModule,
    BannersModule,
    ArticleModule,
    VideoModule,
    AdminModule,
    WxModule,
    ExcelModule, 
  ],
  controllers: [],
  providers: [
    Logger,
    { 
      // 使用全局jwttoken 认证守卫 ，注意守卫顺序
      provide: APP_GUARD,
      useClass: JwtAuthGuard
    },
    {
      // 使用全局 角色权限认证
      provide: APP_GUARD,
      useClass: RolesGuard
    },
  ],
})
// export class AppModule {
//   constructor(private readonly connection: Connection) {} 
// }
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(MiddleLogMiddleware)
      .forRoutes('*');
  } 
} 